package demo2.domain;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/student")
public class StudentController {

    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping("/index")
    List<MaskedStudentRecord> index(
            @RequestParam(name = "firstId", defaultValue = "1") Long firstId,
            @RequestParam(name = "n", defaultValue = "5") Integer n
            ) {
        return studentService.findWithinLimit(firstId, n);
    }

    @GetMapping("/{id}")
    Optional<MaskedStudentRecord> getStudentRecord(@PathVariable("id") Long studentId) {
        return studentService.findById(studentId);
    }

    @PostMapping
    void postStudentRecord(@RequestBody StudentDto dto) {
        Student student = new Student();
        student.setName(dto.getName());
        student.setDob(dto.getDob());
        studentService.save(student);
    }

    @PutMapping("/{id}")
    void modifyStudentRecord(@PathVariable("id") Long studentId, @RequestBody StudentDto dto) {
        Student student = new Student();
        student.setId(studentId);
        student.setName(dto.getName());
        student.setDob(dto.getDob());
        studentService.save(student);
    }

    private static class StudentDto {
        private String name;
        private LocalDate dob;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public LocalDate getDob() {
            return dob;
        }

        public void setDob(LocalDate dob) {
            this.dob = dob;
        }
    }
}
